import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/list/login.vue')
  },
  {
    path: '/',
    name: 'homeview',
    redirect: '/reportsa',
    component: () => import('../views/list/homeview.vue'),
    children: [
      {
        path: '/reportsa',
        name: 'reportsa',
        component: () => import('../views/list/reportsa.vue')
      },
    ]
  },
]
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
import { fn } from '../uitl/router'

function loadRoute() {
  let token = sessionStorage.getItem('token')
  let menulist = JSON.parse(localStorage.getItem('menusList'))
  console.log(123, token); console.log(321, menulist);
  setTimeout(() => {
    if (token && menulist) {
      let newlist = fn(menulist)
      newlist.forEach(item => {
        router.addRoute('homeview', item)
      })
    }
  }, 300)

}
loadRoute()

router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem('token')
  // console.log(token)
  const isLogin = (to.path === '/login')
  // 如果有token，并且是在登录页，那么跳转到首页
  if (token && isLogin) {
    return next({ name: 'homeview' })
  }
  // 如果没有token，并不是在登录页，跳转到登录页
  if (!token && !isLogin) {
    return next({ name: 'login' })
  }
  next()
})
export default router
